<template>
  <div class="search-container">
    <form action="/" class="search-form">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <SearchResult v-if="isResultShow" :searchText="searchText"></SearchResult>
    <SearchSuggestion
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    ></SearchSuggestion>
    <SearchHistory
      v-else
      :SearchHistories="SearchHistories"
      @clearHistories="SearchHistories = []"
      @search="onSearch"
    ></SearchHistory>
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import SearchResult from './components/search-result.vue'
import { setItem, getItem } from '@/utils/storage'
export default {
  name: 'SearchPage',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult,
  },
  props: {},
  data() {
    return {
      searchText: '',
      isResultShow: false,
      SearchHistories: getItem('TOUTIAO_SEARCH_HISTORY') || [],
    }
  },
  computed: {},
  watch: {
    SearchHistories() {
      setItem('TOUTIAO_SEARCH_HISTORY', this.SearchHistories)
    },
  },
  created() {},
  mounted() {},
  methods: {
    onSearch(val) {
      // console.log(val)
      this.searchText = val
      this.isResultShow = true
      const index = this.SearchHistories.indexOf(val)
      if (index !== -1) {
        this.SearchHistories.splice(index, 1)
      }
      this.SearchHistories.unshift(val)
    },
    onCancel() {
      this.$router.back()
    },
  },
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
